package com.wangcang.widgetlibrary.service;

import android.app.Service;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.util.Log;

import com.clj.fastble.BleManager;
import com.clj.fastble.conn.BleCharacterCallback;
import com.clj.fastble.conn.BleGattCallback;
import com.clj.fastble.data.ScanResult;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.ListScanCallback;
import com.wangcang.widgetlibrary.eventbus_event.BluetoothScanResultEvent;
import com.wangcang.widgetlibrary.eventbus_event.CancelScanEvent;
import com.wangcang.widgetlibrary.eventbus_event.ConnectErrorEvent;
import com.wangcang.widgetlibrary.eventbus_event.ConnectEvent;
import com.wangcang.widgetlibrary.eventbus_event.ConnectSuccessEvent;
import com.wangcang.widgetlibrary.eventbus_event.ConnectingEvent;
import com.wangcang.widgetlibrary.eventbus_event.DisConnectedEvent;
import com.wangcang.widgetlibrary.eventbus_event.ScanningEvent;

import de.greenrobot.event.EventBus;

/**
 * Description: 蓝牙扫码枪服务
 * Copyright  : Copyright (c) 2016
 * Author     : yfwang
 * Date       : 2017/6/21 11:23
 */
public class FastLibService extends Service {

    //扫码枪
    private static final String UUID_SERVICE = "0000fff0-0000-1000-8000-00805f9b34fb";
    private static final String UUID_NOTIFY = "0000fff1-0000-1000-8000-00805f9b34fb";
    private BleManager bleManager;
    private boolean isConnect = false;
    private static final long TIME_OUT = 10000;
    private Handler threadHandler = new Handler(Looper.getMainLooper());

    @Nullable

    @Override
    public void onCreate() {
        EventBus.getDefault().register(this);
    }


    private void initData() {
        bleManager = new BleManager(this);
        bleManager.enableBluetooth();
        scanDevice();
    }

    /**
     * 判断是否支持ble
     */
    private boolean isSupportBle() {
        return bleManager.isSupportBle();
    }

    /**
     * 取消搜索
     */
    public void cancelScan() {
        bleManager.cancelScan();
    }


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    public void onEvent(Object event) {
        if (event != null && event instanceof ConnectEvent) {
            cancelScan();
            scanAndConnectWithMAC(((ConnectEvent) event).getMsg());
        } else if (event != null && event instanceof CancelScanEvent) {
            cancelScan();
        }

    }

    /**
     * 扫描出周围所有设备
     */
    public void scanDevice() {
        bleManager.scanDevice(new ListScanCallback(TIME_OUT) {
            @Override
            public void onScanning(final ScanResult result) {
                runOnMainThread(new Runnable() {
                    @Override
                    public void run() {
                        EventBus.getDefault().post(new ScanningEvent(result));
                    }
                });

            }

            @Override
            public void onScanComplete(ScanResult[] results) {

            }
        });
    }


    /**
     * 扫描指定物理地址的设备，并连接
     */
    public void scanAndConnectWithMAC(final String DEVICE_MAC) {
        if (DEVICE_MAC != null)
            bleManager.scanMacAndConnect(
                    DEVICE_MAC,
                    3000,
                    true,
                    new BleGattCallback() {

                        @Override
                        public void onFoundDevice(ScanResult scanResult) {

                        }

                        @Override
                        public void onConnecting(BluetoothGatt gatt, int status) {
                            runOnMainThread(new Runnable() {
                                @Override
                                public void run() {
                                    EventBus.getDefault().post(new ConnectingEvent("Connecting"));
                                }
                            });

                        }

                        @Override
                        public void onConnectError(final BleException exception) {
                            runOnMainThread(new Runnable() {
                                @Override
                                public void run() {
                                    EventBus.getDefault().post(new ConnectErrorEvent(exception.toString()));
                                }
                            });


                        }

                        @Override
                        public void onConnectSuccess(BluetoothGatt gatt, int status) {

                            runOnMainThread(new Runnable() {
                                @Override
                                public void run() {
                                    EventBus.getDefault().post(new ConnectSuccessEvent("ConnectSuccess"));
                                }
                            });

                        }

                        @Override
                        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                            addNotify();
                        }

                        @Override
                        public void onDisConnected(BluetoothGatt gatt, int status, BleException exception) {
                            isConnect = false;
                            runOnMainThread(new Runnable() {
                                @Override
                                public void run() {
                                    EventBus.getDefault().post(new DisConnectedEvent("DisConnected"));
                                }
                            });

                        }

                    });

    }

    /**
     * stop notify
     */
    private boolean stopNotify() {
        return bleManager.stopNotify(UUID_SERVICE, UUID_NOTIFY);
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        initData();
        return START_STICKY;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        bleManager.closeBluetoothGatt();
        stopNotify();
        EventBus.getDefault().unregister(this);
    }


    /**
     * notify
     */
    private void addNotify() {
        runOnMainThread(new Runnable() {
            @Override
            public void run() {
                bleManager.notify(
                        UUID_SERVICE,
                        UUID_NOTIFY,
                        new BleCharacterCallback() {
                            @Override
                            public void onSuccess(final BluetoothGattCharacteristic characteristic) {
                                final byte[] data = characteristic.getValue();
                                Log.e("yfwang", "读取成功" + new String(data));
                                runOnMainThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        EventBus.getDefault().post(new BluetoothScanResultEvent(new String(data)));
                                    }
                                });

                            }

                            @Override
                            public void onFailure(BleException exception) {
                                Log.e("yfwang", "读取失败" + exception.toString());
                            }

                            @Override
                            public void onInitiatedResult(boolean result) {

                            }
                        });
            }
        });


    }


    private void runOnMainThread(Runnable runnable) {
        if (Looper.myLooper() == Looper.getMainLooper()) {
            runnable.run();
        } else {
            threadHandler.post(runnable);
        }
    }


}
